# 胡涵的python工厂
# 开发时间：2021/11/7 14:02
from flask import *
from obs import *
import os
app = Flask(__name__) #一个Flask类对象
app.secret_key='sa51asdasdggasd'
obsClient=ObsClient(
    access_key_id='WERNB32MKVHLHPVUINOQ',
    secret_access_key='gibEX8UWMoQIcuUvpastgGwNwAwmWD4rTDPurQxq',
    server='obs.cn-east-3.myhuaweicloud.com',
) #访问桶
def getobs():  #获取桶内文件名以及文件大小
    file_dict = {}
    resp = obsClient.listObjects('hh-bucket')
    for item in resp.body.contents: #访问obs桶的对象
        size=int(item.size)/1024
        if size<1024:     #文件大小格式转换
            sz=str(round(size,2))+'KB'
        elif 1024<=size<1024*1024:
            sz=str(round(size/1024,2))+'MB'
        else:
            sz=str(round(size/(1024*1024),2))+'GB'
        file_dict[item.key]=sz
    return file_dict
def up():  #上传文件
    f = request.files['file']
    if f:
        file_path = os.path.join('D:\\text', f.filename)
        f.save(file_path)
        obsClient.putFile('hh-bucket',f.filename,file_path)
def download(file): #下载文件到指定目录
    obsClient.getObject('hh-bucket',file,os.path.join('D:\\text',file))
    print('已成功下载')
def delf(file):    #删除文件
    obsClient.deleteObject('hh-bucket',file)
    print('已成功删除')
@app.route('/login',methods=['GET',"POST"])   #声明一个页面，接受请求get 和post
def login(): #登录页面以及验证
    if request.method=='GET':
        return render_template('login.html')   #加载页面
    user=request.form.get('user')    #获取表单值
    pwd=request.form.get('pwd')      #获取表单值
    f = open('user_info.txt')
    dic = eval(f.read())
    f.close()
    for item in dic.keys():
        if user==item and pwd==dic[item]:
            session['user_info']=user
            return redirect('/index')   #跳转到下一个页面
        else:
            pass
    return render_template('login.html',msg='用户名或密码错误!')   #重复渲染当前界面并且返回信息
@app.route('/register',methods=['GET',"POST"])   #声明一个页面，接受请求get 和post
def register(): #注册界面渲染
    return render_template('register.html')
@app.route('/index',methods=['GET','POST']) #声明一个页面，接受请求get
def index(): #网盘页面
    if not session.get('user_info'):
        return redirect('/login')
    file_dict=getobs()
    return render_template('index.html', file=file_dict)
@app.route('/success_reg',methods=['GET','POST']) #声明一个页面，接受请求get,post
def success_reg(): #注册成功
    if request.method=='POST':
        user=request.form.get('us')
        pwd=request.form.get('pw')
        with open('user_info.txt','r+')as f:
            dic = eval(f.read())
        if user in dic.keys():    #判断账户是否存在
            return render_template('register.html', msg='用户名已存在！')
        elif len(pwd)>0 and len(user)>0: #判断输入是否为空
            dic[user]=pwd
            with open('user_info.txt', 'r+')as f:
               f.write(str(dic))
            return redirect('/login')
        else:
            return render_template('register.html', msg='请输入账号密码！')
@app.route('/success_up', methods=['GET', 'POST'])  # 声明一个页面，接受请求get,post
def success_up(): #上传文件成功
    if request.method=='POST':
        up()
        return redirect('/index')
@app.route('/success_down',methods=['GET','POST']) #声明一个页面，接受请求get,post
def success_down(): #下载文件成功
    if request.method=='POST':
        down_f = str(request.form.get('down_file'))  # 获取表单值
        resp = obsClient.listObjects('hh-bucket')
        for item in resp.body.contents:  # 访问obs桶的对象
            if down_f == item.key:
                download(down_f)
                return redirect('/index')
            else:
                pass
        file_dict = getobs()
        return render_template('index.html', file=file_dict, msg1='请输入正确的文件名！')
@app.route('/success_del',methods=['GET','POST']) #声明一个页面，接受请求get,post
def success_del(): #删除文件成功
    if request.method=='POST':
        del_f = str(request.form.get('del_file'))  # 获取表单值
        resp = obsClient.listObjects('hh-bucket')
        for item in resp.body.contents:  # 访问obs桶的对象
            if del_f==item.key:
                delf(del_f)
                return redirect('/index')
            else:
                pass
        file_dict = getobs()
        return render_template('index.html', file=file_dict, msg2='请输入正确的文件名！')
@app.route('/logout',methods=['GET','POST']) #声明一个页面，接受请求get
def logout(): #注销页面
    del session['user_info']
    return redirect('/login')
if __name__=="__main__":
    app.run(host='0.0.0.0',port=8000)